//
//  QianliRefgxfcCqqnbVC.swift
//  todoios
//
//  Created by qianli on 2025/4/22.
//

import Foundation
import UIKit

import SwiftyUserDefaults

class QianliRefgxfcCqqnbVC: QianliParentNaviVC {
    override func GHL4Rhb91XYBer27(){
        self.zdMpsGrNncVEHdYA(title: LocalizedString("REFER & EARN"))
        
        if let topView = self.titleBarView{
            let rightBtn = UIButton(frame: CGRect(x: qianli_pm_width-15 - 80, y: topView.bounds.height/2 - 32/2, width: 80, height: 32))
            topView.addSubview(rightBtn)
            rightBtn.setTitle(LocalizedString("Refer Rules"), for: .normal)
            rightBtn.setTitleColor(.label, for: .normal)
            rightBtn.titleLabel?.font = .systemFont(ofSize: 13)
            rightBtn.touch_With_Block {[weak self](sender) in
                self?.g2bMyYexpIcQOdsO()
            }
        }
        
        let workView = UIView(frame: CGRect(x: 0, y: topSpace+35, width: qianli_pm_width, height: qianli_pm_width-20))
        view.addSubview(workView)
        let circleView = UIView(frame: CGRect(x: qianli_pm_width/4, y: 0, width: qianli_pm_width/2, height: qianli_pm_width/2))
        workView.addSubview(circleView)
        circleView.backgroundColor = .systemBackground
        circleView.layer.cornerRadius = qianli_pm_width/4
        
        let contentView = UIView(frame:CGRect(x: 20, y: 40, width: qianli_pm_width-40, height: workView.bounds.height-40))
        workView.addSubview(contentView)
        contentView.backgroundColor = .systemBackground
        contentView.qianli_round_rect(corner: [.topLeft,.topRight], radii: CGSize(width: 10, height: 10))
        
        let imgview = UIImageView(frame: CGRect(x: contentView.bounds.width/2-81/2, y: 0, width: 81, height: 72))
        contentView.addSubview(imgview)
        imgview.image = "qianli_ic_gmt".qianli_R_image
        
        let titleLabel = UILabel(frame: CGRect(x: 10, y: imgview.frame.maxY+15, width: contentView.bounds.width-20, height: 30))
        contentView.addSubview(titleLabel)
        titleLabel.text = LocalizedString("Refer Friends for Unlimited Time")
        titleLabel.textColor = .label
        titleLabel.font = .boldSystemFont(ofSize: 20)
        titleLabel.textAlignment = .center
        
//        let msgLabel = UILabel(frame: CGRect(x: 25, y: titleLabel.frame.maxY+20, width: contentView.bounds.width-50, height: 100))
//        contentView.addSubview(msgLabel)
//        msgLabel.textColor = .label
//        msgLabel.numberOfLines = 0
//       改用UITextView，以便能点击link字符串触发
        let textView = UITextView(frame: CGRect(x: 25, y: titleLabel.frame.maxY+20, width: contentView.bounds.width-50, height: 120))
        textView.isEditable = false
        textView.isSelectable = true
        textView.delegate = self
        textView.backgroundColor = .clear
        contentView.addSubview(textView)
        
        let invitecode = Defaults[\.invitationCode]
        let str1 = LocalizedString("Have friends install Qianli via your link and enter your ID")
        let str2 = LocalizedString("That's a successful referral")
        let str3 = LocalizedString("Earn 20% extra time FOREVER every time they get a membership!")
        let msg = "\(str1)(\(invitecode))\(str2)；\r\n\(str3)"
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 10 // 设置行距
        
        let myMutableString = NSMutableAttributedString(
                    string: msg,
                    attributes: [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 15),
                                 NSAttributedString.Key.paragraphStyle:paragraphStyle,
                                 NSAttributedString.Key.foregroundColor:UIColor.label])
        let range_1:NSRange = (msg as NSString).range(of:invitecode)
        myMutableString.addAttributes([NSAttributedString.Key.foregroundColor:UIColor(hexString: "#3964ff"),
                                       NSAttributedString.Key.link:URL(string: "action://copyInviteCode") as Any], range: range_1)
        
        let range_2:NSRange = (msg as NSString).range(of:"20%")
        myMutableString.addAttributes([NSAttributedString.Key.foregroundColor:UIColor(hexString: "#ff4949")], range: range_2)
        textView.attributedText = myMutableString
        textView.sizeToFit()
//        msgLabel.attributedText = myMutableString
//        msgLabel.sizeToFit()
        
        let roundView = UIView(frame: CGRect(x: 25, y: contentView.bounds.height-25-42, width: contentView.bounds.width-50, height: 48))
        contentView.addSubview(roundView)
        roundView.backgroundColor = .secondarySystemBackground.withAlphaComponent(0.75)
        roundView.layer.cornerRadius = roundView.bounds.height/2
        let logoView = UIImageView(frame: CGRect(x: 20, y: 8, width: roundView.bounds.height-16, height: roundView.bounds.height-16))
        roundView.addSubview(logoView)
        logoView.image = "qianli_ic_shared".qianli_R_image
        let linkLabel = UILabel(frame: CGRect(x: 20+logoView.bounds.width+10, y: roundView.bounds.height/2 - 20/2, width: 120, height: 20))
        roundView.addSubview(linkLabel)
        linkLabel.font = .systemFont(ofSize: 15)
        linkLabel.textColor = .label
        linkLabel.text = LocalizedString("Share via Link")
        let arrowImg = UIImageView(frame: CGRect(x: roundView.bounds.width-15-8, y: roundView.bounds.height/2-8, width: 8, height: 16))
        roundView.addSubview(arrowImg)
        arrowImg.image = "qianli_row_more".qianli_R_image
        roundView.tap_With_Block {[weak self] in
            self?.HolgCasRFuhOL2or()
        }
        
        // 创建渐变层
        
        let btnCopy = GradientBtn.init(frame: CGRect(x: 45, y: workView.frame.maxY+45, width: 140, height: 40), title: LocalizedString("Copy My Code"))
        view.addSubview(btnCopy)
        btnCopy.touch_With_Block {[weak self] sender in
            self?.KTZQ3exUn43xR42Z()
        }
        
        let btnFriend = GradientBtn.init(frame: CGRect(x: qianli_pm_width-45-140, y: workView.frame.maxY+45, width: 140, height: 40), title: LocalizedString("My Referrals"))
        view.addSubview(btnFriend)
        btnFriend.touch_With_Block {[weak self] sender in
            let detailVC = QianliInviteDetail()
            detailVC.modalPresentationStyle = .overFullScreen
            self?.present(detailVC, animated: true)
        }
        
        let btnInput = UIButton(frame: CGRect(x: qianli_pm_width/2-150/2, y: qianli_pm_height-100, width: 150, height: 30))
        view.addSubview(btnInput)
        btnInput.setTitle(LocalizedString("Click to Enter Code"), for: .normal)
        btnInput.setTitleColor(UIColor(hexString: "#3964ff"), for: .normal)
        btnInput.titleLabel?.font = .systemFont(ofSize: 16)
        btnInput.touch_With_Block { [weak self] sender in
            self?.Rj7jOcnmcmlyogqu()
        }
    }
    
    private func g2bMyYexpIcQOdsO(){
//自定义UIAlertController样式
        let msg_1 = "5o6o6I2Q6KeE5YiZ5aW95Y+L6aaW5qyh5a6J6KOF5Y2D6YeM5Yqg6YCf5Zmo5ZCO5aGr5YaZ5oKo55qESUTljbPnrpfmjqjojZDmiJDlip/vvJs=".qianli_safe_base64_decode()
        let msg_2 = "5o6o6I2Q55qE5pyL5Y+L6LSt5Lmw5oiW5LuO5YW25LuW5o6o6I2Q5Lq65aSE6I635b6X5Lya5ZGY5pe277yM5oKo6YO95bCG6JaF5Y+WMjAl55qE5aWW5Yqx77yb".qianli_safe_base64_decode()
        let msg_7 = "6I636LWg55qE5Lya5ZGY5LiO6LSm5oi357qn5Yir5LiA6Ie077yM5aaC5p6c5LiN5piv5Lya5ZGY77yM5YiZ6LWg6YCB5pmu6YCa5Lya5ZGY44CC".qianli_safe_base64_decode()
        do{
            var message = "\n\(msg_1!)\(msg_2!)\n"
            message = message + "举个例子:\n"
            message = message + "\("QeaOqOiNkELvvIxC5o6o6I2QQ++8mw==".qianli_safe_base64_decode()!)\n"
            message = message + "\("QuS5sOW5tOWNoeS8muWRmO+8jEHojrflvpc3M+WkqeS8muWRmOOAgg==".qianli_safe_base64_decode()!)\n"
            message = message + "\("Q+S5sOW5tOWNoeS8muWRmO+8jELojrflvpc3M+WkqeS8muWRmO+8jEHojrflvpcxNeWkqeS8muWRmO+8mw==".qianli_safe_base64_decode()!)\n"
            message = message + "\("5YWz57O75rC45LmF57uR5a6a5LiU5rKh5pyJ5LiL6ZmQ77yB".qianli_safe_base64_decode()!)\n"
            message = message + "\(msg_7!)\n"
            
            let attributedMessage = NSMutableAttributedString(string: message)
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineSpacing = 10 // 设置行间距，可根据需要调整
    //        attributedMessage.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: message.count))
            attributedMessage.addAttributes([NSAttributedString.Key.paragraphStyle:paragraphStyle,
                                             NSAttributedString.Key.font:UIFont.systemFont(ofSize: 15)], range: NSRange(location: 0, length: message.count))
            
            let alert = UIAlertController(title: LocalizedString("Refer Rules"), message: nil, preferredStyle:.alert)
            alert.setValue(attributedMessage, forKey: "attributedMessage")
    //同理attributedTitle可以设置Alert的标题样式
    //      alert.setValue(attributedTitle, forKey: "attributedTitle")
            alert.addAction(UIAlertAction(title: LocalizedString("SURE"), style:.default, handler: nil))
            present(alert, animated: true, completion: nil)
            
        }catch{
            print("err:",error.localizedDescription)
        }
        
    }
}

extension QianliRefgxfcCqqnbVC:UITextViewDelegate{
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        if URL.absoluteString == "action://copyInviteCode" {
            KTZQ3exUn43xR42Z()
            return false
        }
        return true
    }
    
    private func KTZQ3exUn43xR42Z(){
        let invitecode = Defaults[\.invitationCode]
        UIPasteboard.general.string = invitecode
        let alert = UIAlertController(title: LocalizedString("Infomation"), message:LocalizedString("Your ID copied!"), preferredStyle:.alert)
        alert.addAction(UIAlertAction(title: LocalizedString("SURE"), style:.default, handler: nil))
        present(alert, animated: true, completion: nil)
    }
    
    private func HolgCasRFuhOL2or(){
        let backView = UIView(frame: CGRect(x: 0, y: 0, width: qianli_pm_width, height: qianli_pm_height))
        view.addSubview(backView)
        backView.backgroundColor = .black.withAlphaComponent(0.65)
        
        let msgView = UIView(frame: CGRect(x: 20, y: qianli_pm_height/2-300/2, width: qianli_pm_width-40, height: 300))
        backView.addSubview(msgView)
        msgView.backgroundColor = .secondarySystemBackground
        msgView.layer.cornerRadius = 20
        msgView.tap_With_Block {
            //防止穿透
        }
        
        let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: msgView.bounds.width, height: 80))
        msgView.addSubview(titleLabel)
        titleLabel.text = LocalizedString("Referral Link")
        titleLabel.font = .boldSystemFont(ofSize: 18)
        titleLabel.textColor = .label
        titleLabel.textAlignment = .center
        let subLabel = UILabel(frame: CGRect(x: 0, y: 80, width: msgView.bounds.width, height: 20))
        msgView.addSubview(subLabel)
        subLabel.text = LocalizedString("Qianli Speed Starts Now!")
        subLabel.textColor = .label
        subLabel.font = .systemFont(ofSize: 15)
        subLabel.textAlignment = .center
        let msgLabel = UILabel(frame: CGRect(x: 20, y: subLabel.frame.maxY+30, width: msgView.bounds.width-40, height: 60))
        msgView.addSubview(msgLabel)
        msgLabel.numberOfLines = 0
        msgLabel.textColor = .label
        msgLabel.font = .systemFont(ofSize: 15)
        let frontendUrl = Defaults[\.frontendUrl]
        let invitecode = Defaults[\.invitationCode]
        let shareUrl = "\(frontendUrl)/#/login?aff=\(invitecode)"
        let message = "\(LocalizedString("Download Link (Chrome recommended)"))：\(shareUrl)" //下载链接（推荐使用Chrome浏览器访问）
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 10
        let attributedMessage = NSMutableAttributedString(string: message)
        attributedMessage.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: message.count))
        msgLabel.attributedText = attributedMessage
        msgLabel.sizeToFit()
        
        
        let btnCopy = GradientBtn.init(frame: CGRect(x: msgView.bounds.width/2 - 130/2, y: msgView.bounds.height-40-42, width: 130, height: 40), title: LocalizedString("Copy Referral Link"))
        msgView.addSubview(btnCopy)
        btnCopy.touch_With_Block {[weak self] sender in
            UIPasteboard.general.string = shareUrl
            let alert = UIAlertController(title: LocalizedString("Infomation"), message: LocalizedString("Copied to clipboard!"), preferredStyle:.alert)
            alert.addAction(UIAlertAction(title: LocalizedString("SURE"), style:.default, handler: nil))
            self?.present(alert, animated: true, completion: nil)
        }

        let btn = UIButton(frame: CGRect(x: qianli_pm_width/2 - 30/2, y: msgView.frame.maxY+30, width: 30, height: 30))
        backView.addSubview(btn)
        btn.setImage("qianli_alert_btclose".qianli_R_image, for: .normal)
        btn.touch_With_Block { [weak msgView,weak btn,weak backView](sender) in
            if let msgV = msgView{
                for childv in msgV.subviews {
                    childv.removeFromSuperview()
                }
                msgV.removeFromSuperview()
            }
            msgView = nil
            
            btn?.removeFromSuperview()
            btn = nil
            
            backView?.removeFromSuperview()
            backView = nil
        }

        backView.tap_With_Block {[weak msgView,weak btn,weak backView] in
            if let msgV = msgView{
                for childv in msgV.subviews {
                    childv.removeFromSuperview()
                }
                msgV.removeFromSuperview()
            }
            msgView = nil
            
            btn?.removeFromSuperview()
            btn = nil
            
            backView?.removeFromSuperview()
            backView = nil
        }
        
    }
    
    private func Rj7jOcnmcmlyogqu() {
        let alertController = UIAlertController(title: LocalizedString("Enter Invitation Code"), message: LocalizedString("Enter the invitation code to bind"), preferredStyle:.alert)

        // 添加输入框
        alertController.addTextField { (textField) in
            textField.placeholder = LocalizedString("Enter Invitation Code")//"请输入邀请码"
            textField.keyboardType = .default
        }

        // 添加取消按钮
        let cancelAction = UIAlertAction(title: LocalizedString("CANCEL"), style:.cancel, handler: nil)
        alertController.addAction(cancelAction)

        // 添加确定按钮
        let okAction = UIAlertAction(title: LocalizedString("SURE"), style:.default) { [weak self,weak alertController] (action) in
            if let textField = alertController?.textFields?.first, let inputText = textField.text {
//                print("您输入的邀请码: \(inputText)")
                self?.dcJBvyIuVQUkCeKO(inputText)
            }
        }
        alertController.addAction(okAction)
        // 展示弹窗
        present(alertController, animated: true, completion: nil)
    }
    
    private func dcJBvyIuVQUkCeKO(_ inviteCode:String){
        if(inviteCode.isEmpty){
            self.alert_qianli_message(LocalizedString("Error Invitation Code"), message: LocalizedString("Invitation Code Couldn't be Null"))
        }else if (inviteCode.count<4 || inviteCode.count>20){
            self.alert_qianli_message(LocalizedString("Error Invitation Code"), message: LocalizedString("Please enter a valid invitation code!"))
        }else{
            UserInfoViewModel.shared.BfVcQQfbTmL5UsRU(inviteCode)
            UserInfoViewModel.shared.completionMsgHandler = { [weak self] result,msg in
                DispatchQueue.main.async {
                    self?.view.Qianli_Toast(msg)
                }
            }
        }
        
    }
    
}
